<script setup lang="ts">
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { register, sendEmail, getTotalUsers } from '../api/auth'
import { ElMessage, ElNotification } from 'element-plus'
import { User, Lock, Message, Key } from '@element-plus/icons-vue'

// 表单接口定义
interface from {
  username: string;
  password: string;
  email: string;
  code: string;
  merchantId?: string;
}

// 表单数据
const formData = reactive<from>({
  username: '',
  password: '',
  email: '',
  code: ''
})

// 表单规则
const rules = {
  username: [
    { required: true, message: '请输入商户名称', trigger: 'blur' },
    { min: 3, message: '商户名称长度不能小于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

const router = useRouter()
const formRef = ref<any>()

// 注册状态
const loading = ref<boolean>(false)

// 验证码状态
const codeLoading = ref<boolean>(false)
const codeCountdown = ref<number>(0)
const codeTimer = ref<number | null>(null)

// 生成商户ID
const generateMerchantId = async (): Promise<string> => {
  try {
    // 获取用户总数
    const response = await getTotalUsers();
    
    if (response.data && response.data.code === 200) {
      const userCount = response.data.data || 0;
      return `M25${String(userCount + 1).padStart(3, '0')}`;
    }
  } catch (error) {
    console.error('获取用户总数失败:', error);
  }
  
  // 如果获取失败，使用时间戳生成
  return `M25${Date.now().toString().slice(-3)}`;
}

// 注册方法
const registerFn = async (): Promise<void> => {
  // 验证表单，如果无效则返回
  if (!formRef.value || !(await formRef.value.validate().catch(() => false))) return
  
  // 设置加载状态
  loading.value = true
  try {
    // 生成商户ID
    formData.merchantId = await generateMerchantId();
    
    // 调用注册API
    const { data } = await register(formData)
    
    // 处理响应
    if ((data.code === 200 || data.code === 201) && data.data) {
      // 显示注册成功通知
      ElNotification({
        title: '注册成功',
        message: '正在跳转到登录页...',
        type: 'success',
        duration: 3000
      })
      
      // 3秒后跳转到登录页
      setTimeout(() => router.push('/login'), 3000)
    } else {
      // 显示注册失败通知
      ElNotification({
        title: '注册失败',
        message: data.message || '请稍后再试',
        type: 'error',
        duration: 3000
      })
    }
  } catch (error: any) {
    // 处理注册异常
    ElNotification({
      title: '注册失败',
      message: error.response?.data?.message || '请稍后再试',
      type: 'error',
      duration: 3000
    })
  } finally {
    // 无论成功失败，重置加载状态
    loading.value = false
  }
}

// 获取邮箱验证码
const getEmail = async (): Promise<void> => {
  // 验证邮箱格式
  if (!formData.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }
  
  // 设置加载状态
  codeLoading.value = true
  try {
    // 发送验证码API
    await sendEmail({ email: formData.email })
    
    // 设置倒计时
    codeCountdown.value = 60
    
    // 如果之前的定时器存在就清除
    if (codeTimer.value) clearInterval(codeTimer.value)
    
    // 创建新的倒计时定时器
    codeTimer.value = window.setInterval(() => {
      if (codeCountdown.value > 0) codeCountdown.value--
      else if (codeTimer.value) {
        // 倒计时结束，清除定时器
        clearInterval(codeTimer.value)
        codeTimer.value = null
      }
    }, 1000)
    
    // 发送成功通知
    ElNotification({
      title: '验证码已发送',
      message: '请查收您的邮箱',
      type: 'success',
      duration: 3000
    })
  } catch (error: any) {
    // 处理发送异常
    ElNotification({
      title: '发送失败',
      message: error.response?.data?.message || '验证码发送失败，请稍后再试',
      type: 'error',
      duration: 3000
    })
  } finally {
    // 无论成功失败，重置加载状态
    codeLoading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => router.push('/login')

// 组件卸载时清除定时器
onUnmounted(() => {
  if (codeTimer.value) clearInterval(codeTimer.value)
})
</script>

<template>
  <div class="register-container">
    <div class="register-header">
      <div class="logo-container">
        <h1 class="system-title">Zeno电商管理系统</h1>
      </div>
    </div>
    
    <el-card class="register-card">
      <template #header>
        <h2 class="card-header">账号注册</h2>
      </template>
      
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="rules"
        label-position="top"
        @submit.prevent="registerFn"
      >
        <!-- 商户名称 -->
        <el-form-item label="商户名称" prop="username">
          <el-input 
            v-model="formData.username"
            placeholder="请输入商户名称"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
            size="large"
            prefix-icon="Lock"
          />
        </el-form-item>
        
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="formData.email"
            type="email"
            placeholder="请输入邮箱"
            size="large"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <!-- 邮箱验证码 -->
        <el-form-item label="邮箱验证码" prop="code">
          <div class="code-input-group">
            <el-input 
              v-model="formData.code"
              placeholder="请输入邮箱验证码"
              size="large"
              prefix-icon="Key"
            />
            <el-button 
              type="primary"
              @click="getEmail" 
              :loading="codeLoading"
              :disabled="codeCountdown > 0"
              class="code-btn"
              size="large"
            >
              {{ codeCountdown > 0 ? `${codeCountdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 注册按钮 -->
        <el-button 
          type="primary" 
          @click="registerFn" 
          :loading="loading" 
          class="submit-btn"
          size="large"
        >
          {{ loading ? '注册中...' : '立即注册' }}
        </el-button>
        
        <!-- 登录页链接 -->
        <div class="form-links">
          <el-link type="primary" @click="goToLogin">已有账号？直接登录</el-link>
        </div>
      </el-form>
    </el-card>
    
    <div class="register-footer">
      <p>Zeno电商管理系统 &copy; 2023 版权所有</p>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.register-header {
  padding: 40px 0 20px;
  text-align: center;
}

.system-title {
  font-size: 24px;
  font-weight: 500;
  color: var(--primary-color, #e1251b);
  margin: 0;
}

.register-card {
  width: 450px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.code-btn {
  width: 120px;
  white-space: nowrap;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
  height: 44px;
  font-size: 16px;
}

.form-links {
  text-align: center;
  margin-top: 16px;
}

.register-footer {
  margin-top: auto;
  padding: 20px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

:deep(.el-button--primary) {
  background-color: var(--primary-color, #e1251b);
  border-color: var(--primary-color, #e1251b);
}

:deep(.el-button--primary:hover) {
  background-color: var(--primary-hover, #c81623);
  border-color: var(--primary-hover, #c81623);
}

:deep(.el-link--primary) {
  color: var(--primary-color, #e1251b);
}
</style> 